package src

/*
#include "fvad.h"
*/
import "C"
import (
	"encoding/binary"
	"fmt"
	"io/ioutil"
	"os"
)

var inst *C.struct_Fvad

func VadTest(filename string, sampleRate int, sampleTime int) {
	fmt.Println("filename:" + filename)
	file, e := os.Open("sample/" + filename)
	if nil == e {
		bytes, _ := ioutil.ReadAll(file)
		VadCheck(bytes, sampleRate, sampleTime)
	}
}

//初始化vad
func VadCheck(bytes []byte, sampleRate int, sampleTime int) {
	var total float32 = 0
	var active float32 = 0
	var frameSize = sampleRate / (1000 / sampleTime)
	length := len(bytes)
	current := 0
	inst = C.fvad_new()
	C.fvad_set_mode(inst, C.int(2))
	C.fvad_set_sample_rate(inst, C.int(sampleRate))
	//读取FRAME
	frames := make([]C.short, frameSize)
	ok := true
	for ok {
		for i := 0; i < frameSize; i++ {
			if current+2 < length {
				current += 2
				tmp := bytes[current : current+2]
				u := binary.LittleEndian.Uint16(tmp)
				frames[i] = C.short(u)
			} else {
				ok = false
			}
		}
		if ok {
			result := int(C.fvad_process(inst, &frames[0], C.ulong(frameSize)))
			if 1 == result {
				active += 1
			}
			total += 1
			//fmt.Print(strconv.Itoa(result))
		}
	}
	fmt.Printf("%3.2f\n", active/total*100)
	defer C.fvad_free(inst)
}
